package com.example.demo.thread.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * 读写锁使用方法（读写锁是一种改进型的排它锁，也被称为共享/排它锁）
 *
 * @author: htc
 * @date: Created in 10:06 2019/1/8.
 */
public class ReadWriteLockUsage {
    /**
     * ReentrantReadWriteLock所实现的读写锁是个可重入锁，且支持锁的降级(Downgrage)
     * 即一个线程在持有读写锁的写锁情况下可以继续获得相应的读锁
     */
    private final ReadWriteLock rwLock = new ReentrantReadWriteLock();

    private final Lock readLock = rwLock.readLock();

    private final Lock writeLock = rwLock.writeLock();

    /**
     * 读线程执行该方法
     */
    public void reader(){
        //申请读锁
        readLock.lock();
        try {
            //在此区域读取共享变量
        } finally {
            //在finally块中释放锁，以免锁泄露
            readLock.unlock();
        }
    }

    public void writer(){
        //申请读锁
        writeLock.lock();

        try {
            //在此区域访问(读、写)共享变量
        } finally {
            writeLock.unlock();
        }
    }
}
